"use client"
import { useEffect, useRef, useState } from 'react';
import { Canvas, FabricText, FabricImage, Line,FabricObject,Gradient,Shadow ,TEvent,Textbox} from 'fabric';
import { toast } from '@/hooks/use-toast'
import { 
  Monitor, 
  Smartphone, 
  Eraser, 
  Type, 
  ImageIcon, 
  Grid, 
  Layers, 
  Trash2,
  Undo2,
  Redo2,
  Download,
  MoreHorizontal
} from 'lucide-react';
// @ts-ignore
import WebFont from 'webfontloader';
import {
  Tooltip,
  TooltipContent,
  TooltipTrigger,
  TooltipProvider
} from "@/components/ui/tooltip"
import { Button } from "@/components/ui/button"
import { Input } from "@/components/ui/input"
import { Label } from "@/components/ui/label"
import { Separator } from "@/components/ui/separator"
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu"
import {
  Dialog,
  DialogContent,
  DialogHeader,
  DialogTitle,
  DialogTrigger,
} from "@/components/ui/dialog"

interface Tool {
  text: string;
  url: string;
}

interface Template {
  name: string;
  image: string;
  title: string;
  json: string;
  ispc:boolean;
}



const HomePage = () => {
  const canvasRef = useRef<HTMLCanvasElement>(null);
  const [canvas, setCanvas] = useState<Canvas | null>(null);
  const [isPc, setIsPc] = useState(true);
  const [bgColor, setBgColor] = useState('#FFFFFF');
  const [showGrid, setShowGrid] = useState(false);
  const [selectedObject, setSelectedObject] = useState<FabricObject | null>(null);
  const [dialogOpen, setDialogOpen] = useState(false);
  
  useEffect(() => {
    // 加载自定义字体
    if (typeof window !== 'undefined') {
     // 只在客户端加载字体
        WebFont.load({
          google: {
            families: [
              'Open Sans:400,700',
              'Roboto:400,700',
              'Lato:400,700',
              'Montserrat:400,700',
              'Raleway:400,700',
              'Poppins:400,700',
              'Noto Sans:400,700'
            ]
          },
          custom: {
            families: [
              '优设标题黑',
              '锐字真言体',
              '站酷文艺体',
              '站酷快乐体',
              '胡晓波男神体',
              '仓耳小丸子',
              '阿里巴巴普惠体-Bold',
              '思源宋体-Bold'
            ], 
            urls: [
              '/fonts/youshebiaotihei.css', // 字体文件的路径
              '/fonts/YueZiZhenYan.css',
              '/fonts/ZhanKuWenYiTi.css',
              '/fonts/ZhanKuKuaiLe.css',
              '/fonts/huxiaobonanshen.css',
              '/fonts/xiaowanzi.css',
              '/fonts/alipuhui_2_85_bold.css',
              '/fonts/SourceHanSerifCN-Bold.css'
            ]
          },
          active: () => {
            console.log('字体加载完成'); // 添加调试信息
          },
          inactive: () => {
            console.log('字体加载失败'); // 添加错误处理
          }
        });
      }
  }, []);

  // 修改字体选择器
  const fontOptions = [
    '优设标题黑', 
    '锐字真言体',
    '站酷文艺体',
    '站酷快乐体',
    '胡晓波男神体',
    '仓耳小丸子',
    '阿里巴巴普惠体-Bold',
    '思源宋体-Bold',
    'Open Sans',  
    'Roboto',    
    'Lato',      
    'Montserrat',
    'Raleway',   
    'Poppins',   
    'Noto Sans'  
  ];

  const [textItem, setTextItem] = useState({
    fontSize: 80,
    fontFamily: '优设标题黑',
    textColor: '#FFA500',
    fontWeight: 500,
    stroke: '#000000',
    strokeWidth: 0,
    shadow: {
      color: 'rgba(0,0,0,0.5)',
      blur: 5,
      offsetX: 2,
      offsetY: 2
    }
  });

  const [imageItem, setImageItem] = useState({
    scaleX: 0.5,
    scaleY: 0.5,
    stroke: '#000000',
    strokeWidth: 0,
    shadow: {
      color: 'rgba(0,0,0,0.5)',
      blur: 5,
      offsetX: 2,
      offsetY: 2,
    }
  });
  const [templates, setTemplates] = useState<Template[]>([]);


  useEffect(() => {
    setTemplates([
      {
        name: '极简课程模板',
        title: '极简课程模板', 
        image:'/images/极简课程模板.png',
        json: '/json/极简课程模板.json',
        ispc: true
      },
      {
        name: '系列教程模板',
        title: '教程模板',
        image:'/images/系列教程模板.png',
        json: '/json/系列教程模板.json',
        ispc: true
      },
      {
        name: '科技数码模板',
        title: '科技数码模板', 
        image:'/images/科技数码模板.png',
        json: '/json/科技数码模板.json',
        ispc: true
      },
      {
        name: '手机端课程模板',
        title: '手机端课程模板',
        image:'/images/手机端课程模板.png',
        json: '/json/手机端课程模板.json',
        ispc: false
      },
     
    ]);
  }, []);


  const tools: Tool[] = [
    { text: '图片去背景', url: 'https://cutout.aiwave.cc/' },
    { text: '截图美化', url: 'https://shots.so/' },
    { text: '产品图制作', url: 'https://www.x-design.com/product-shoot' },
    { text: '图标素材', url: 'https://www.iconfont.cn/' },
  ];

  useEffect(() => {
    if (canvasRef.current) {
      const newCanvas = new Canvas(canvasRef.current, {
        width: isPc ? 1200 : 720*3/5,
        height: isPc ? 720 : 1200*3/5,
        backgroundColor: new Gradient({
          type: 'linear',
          coords: {
            x1: 0,
            y1: 0,
            x2: isPc ? 1200 : 720,
            y2: 0
          },
          colorStops: [
            { offset: 0, color: '#FF6688' },  // 降低饱和度的粉色
            { offset: 1, color: '#AA66CC' }   // 降低饱和度的紫色
          ]
        }),
        selection: true
      });
      newCanvas.renderAll()
      setCanvas(newCanvas);

      return () => {
        newCanvas.dispose();
      };
    }
  }, [isPc]);


useEffect(() => {
  if (canvas) {
    if (showGrid) {
      // 添加网格
      const gridSize = 10;
      const gridColor = 'rgba(0,0,0,0.1)';
      const width = canvas.getWidth();
      const height = canvas.getHeight();
      
      // 创建垂直线
      for (let i = 0; i <= width; i += gridSize) {
        canvas.add(new Line([i, 0, i, height], {
          stroke: gridColor,
          selectable: false,
          evented: false
        }));
      }
      
      // 创建水平线
      for (let i = 0; i <= height; i += gridSize) {
        canvas.add(new Line([0, i, width, i], {
          stroke: gridColor,
          selectable: false,
          evented: false
        }));
      }
    } else {
      // 移除网格
      canvas.getObjects().forEach(obj => {
        if (obj.type === 'line') {
          canvas.remove(obj);
        }
      });
    }
    canvas.renderAll();
  }
}, [showGrid, canvas]);

useEffect(() => {
  if (canvas) {
    const handleSelection = () => {
      const activeObject = canvas.getActiveObject();
      // console.log('Selected object:', activeObject); // 调试信息
      setSelectedObject(activeObject || null);

       // 同步状态到输入框
       if (activeObject && activeObject.type === 'textbox') {
        const textObj = activeObject as Textbox;
        setTextItem({
          fontSize: textObj.fontSize || 80,
          fontFamily: textObj.fontFamily || '优设标题黑',
          textColor: textObj.fill?.toString() || '#FFA500',
          fontWeight: Number(textObj.fontWeight) || 500,
          stroke: textObj.stroke?.toString() || '#000000',  // Add this
          strokeWidth: textObj.strokeWidth || 0,           // Add this
          shadow: {
            color: textObj.shadow?.color || 'rgba(0,0,0,0.5)',
            blur: textObj.shadow?.blur || 5,
            offsetX: textObj.shadow?.offsetX || 2,
            offsetY: textObj.shadow?.offsetY || 2
          },
        });
      } else if (activeObject && activeObject.type === 'image') {
        const imgObj = activeObject as FabricImage;
          setImageItem({
            scaleX: imgObj.scaleX || 0.5,
            scaleY: imgObj.scaleY || 0.5,
            stroke: imgObj.stroke?.toString() || '#000000',
            strokeWidth: imgObj.strokeWidth || 0,
            shadow: {
              color: imgObj.shadow?.color || 'rgba(0,0,0,0.5)',
              blur: imgObj.shadow?.blur || 5,
              offsetX: imgObj.shadow?.offsetX || 2,
              offsetY: imgObj.shadow?.offsetY || 2
            }
          });
      }
    };


    canvas.on('selection:created', handleSelection);
    canvas.on('selection:updated', handleSelection);
    canvas.on('selection:cleared', () => {
      console.log('Selection cleared'); // 调试信息
      setSelectedObject(null);
    });

    return () => {
      canvas.off('selection:created', handleSelection);
      canvas.off('selection:updated', handleSelection);
      canvas.off('selection:cleared');
    };
  }
}, [canvas]);

const changeLinearBgColor = (color: string) => {
  if (!canvas) return;

  // Extract color stops from gradient string
  const colorStops = color.match(/#[0-9a-fA-F]{6}|rgb\([^)]+\)/g) || [];
  
  // Extract angle from gradient string
  const angleMatch = color.match(/(\d+)deg/);
  const angle = angleMatch ? parseInt(angleMatch[1]) : 0;
  
  // Convert angle to radians
  const radians = (angle * Math.PI) / 180;
  
  // Calculate gradient direction based on angle
  const width = canvasRef.current?.parentElement?.clientWidth || 1200;
  const height = canvas.getHeight();
  const x2 = Math.cos(radians) * width;
  const y2 = Math.sin(radians) * height;

  // Create gradient configuration
  const gradientConfig = {
    type: 'linear' as const,
    coords: {
      x1: 0,
      y1: 0,
      x2: x2,
      y2: y2
    },
    colorStops: colorStops.map((color, index, arr) => ({
      offset: index / (arr.length - 1),
      color: color
    }))
  };

  // Set background with gradient
  canvas.set('backgroundColor', new Gradient(gradientConfig));
  canvas.renderAll();
};

const handleCopy = async () => {
  if (!canvas) return;
  
  const activeObject = canvas.getActiveObject();
  if (!activeObject) {
    toast({
      title: "请先选择一个对象",
      variant: "destructive",
    });
    return;
  }

  try {
    const cloned = await activeObject.clone();
    cloned.set({
      left: (activeObject.left || 0) + 10,
      top: (activeObject.top || 0) + 10
    });
    canvas.add(cloned);
    canvas.setActiveObject(cloned);
    canvas.renderAll();
    toast({
      title: "复制成功",
      variant: "default",
    });
  } catch (error) {
    console.error('复制失败:', error);
    toast({
      title: "复制失败",
      variant: "destructive",
    });
  }
};


const handleImageUpload = (e: React.ChangeEvent<HTMLInputElement>) => {
  const file = e.target.files?.[0];
  if (!file || !canvas) return;

  const reader = new FileReader();
  reader.onload = (event) => {
    const img = new Image();
    img.src = event.target?.result as string;
    
    img.onload = () => {
      const fabricImage = new FabricImage(img, {
        left: isPc ? 400 : 220,
        top: 200,
        scaleX: imageItem.scaleX,  // 使用 imageItem 的 scaleX
        scaleY: imageItem.scaleY,  // 使用 imageItem 的 scaleY
        stroke: imageItem.stroke,  // 使用 imageItem 的 stroke
        strokeWidth: imageItem.strokeWidth,  // 使用 imageItem 的 strokeWidth
        shadow: new Shadow(imageItem.shadow)  // 使用 imageItem 的 shadow
      });
      canvas.add(fabricImage);
      canvas.renderAll();
    };
  };
  reader.readAsDataURL(file);
};

 // Add these helper functions
 const updateObjectProperty = (property: string, value: any) => {
  if (selectedObject && canvas) {
    selectedObject.set(property, value);
    canvas.renderAll();
  }
};


const handleColorChange = (color: string) => {
  if (selectedObject) {
    updateObjectProperty('fill', color);
  }
};




  const setSize = (size: 'pc' | 'phone') => {
    setIsPc(size === 'pc');
  };

  const addText = () => {
    if (canvas) {
      const text = new Textbox('修改文本', {
        left: isPc ? 400 : 220,
        top: 200,
        fontSize: textItem.fontSize,
        fontFamily: textItem.fontFamily,
        fill: textItem.textColor,
        fontWeight: Number(textItem.fontWeight),
        stroke: textItem.stroke,
        strokeWidth: textItem.strokeWidth,
        shadow: new Shadow({
          color: textItem.shadow.color,
          blur: textItem.shadow.blur,
          offsetX: textItem.shadow.offsetX,
          offsetY: textItem.shadow.offsetY
        }),
        editable: true,
        hasControls: true,
        hasBorders: true,
        editingBorderColor: 'blue',
        splitByGrapheme: true ,
        width: 400, 
      });
      text.enterEditing();
     

      canvas.add(text);
      canvas.setActiveObject(text);
      canvas.renderAll();
    }
  };


  const clearBg = () => {
    if (canvas) {
      canvas.backgroundColor='#fff'
      canvas.renderAll();
    }
  };

  const applyTemplate = async (template: Template) => {
    try {
      const response = await fetch(template.json);
      const json = await response.json();
      if (canvas) {
        canvas.clear();
        // 根据模板的ispc属性调整画布尺寸
          const newWidth = template.ispc ? 1200 : 720*3/5;
          const newHeight = template.ispc ? 720 : 1200*3/5;
          
          // 立即设置画布尺寸
          canvas.setDimensions({
            width: newWidth,
            height: newHeight
          });
        

        await canvas.loadFromJSON(json);
        canvas.requestRenderAll();
        toast({
          title: `应用模板: ${template.title}`,
          variant: "default",
        });
         // 关闭对话框
      setDialogOpen(false); // Add this line
      }
    } catch (error) {
      console.error('应用模板失败:', error);
      toast({
        title: "应用模板失败",
        variant: "destructive",
      });
    }
  };

  
interface HistoryItem {
  action: 'add' | 'remove' | 'modify';
  object: FabricObject;
  state?: any;
}

const [undoHistory, setUndoHistory] = useState<HistoryItem[]>([]);
const [redoHistory, setRedoHistory] = useState<HistoryItem[]>([]);

const addToHistory = (action: HistoryItem['action'], object: FabricObject) => {
  const clonedObject = object.toObject();
  setUndoHistory(prev => [...prev, { action, object, state: clonedObject }]);
  setRedoHistory([]); // 清空重做历史
};

useEffect(() => {
  if (canvas) {
    // 定义事件处理函数
    const handleAdded = (e: { target: FabricObject }) => {
      if (e.target) {
        addToHistory('add', e.target);
      }
    };

    const handleRemoved = (e: { target: FabricObject }) => {
      if (e.target) {
        addToHistory('remove', e.target);
      }
    };

    const handleModified = (e: { target: FabricObject }) => {
      if (e.target) {
        addToHistory('modify', e.target);
      }
    };

    // 添加事件监听
    canvas.on('object:added', handleAdded);
    canvas.on('object:removed', handleRemoved);
    canvas.on('object:modified', handleModified);

    return () => {
      // 移除事件监听
      canvas.off('object:added', handleAdded);
      canvas.off('object:removed', handleRemoved);
      canvas.off('object:modified', handleModified);
    };
  }
}, [canvas]);


const handleAdded = (e: { target: FabricObject }) => {
  if (e.target) addToHistory('add', e.target);
};
const handleRemoved = (e: { target: FabricObject }) => {
  if (e.target) addToHistory('remove', e.target);
};
const handleModified = (e: { target: FabricObject }) => {
  if (e.target) addToHistory('modify', e.target);
};

const handleUndo = () => {
  if (undoHistory.length > 0 && canvas) {
    // 暂停历史记录
    canvas.off('object:added');
    canvas.off('object:removed');
    canvas.off('object:modified');

    const lastAction = undoHistory[undoHistory.length - 1];
    setUndoHistory(prev => prev.slice(0, -1));
    setRedoHistory(prev => [...prev, lastAction]);

    switch (lastAction.action) {
      case 'add':
        canvas.remove(lastAction.object);
        break;

      case 'remove':
        canvas.add(lastAction.object);
        break;

      case 'modify':
        if (lastAction.state) {
          lastAction.object.set(lastAction.state);
          lastAction.object.setCoords();
        }
        break;
    }

    // 恢复历史记录
    canvas.on('object:added', handleAdded);
    canvas.on('object:removed', handleRemoved);
    canvas.on('object:modified', handleModified);

    canvas.requestRenderAll();
  }
};


const handleRedo = () => {
  if (redoHistory.length > 0 && canvas) {
    // 暂停历史记录
    canvas.off('object:added');
    canvas.off('object:removed');
    canvas.off('object:modified');

    const lastAction = redoHistory[redoHistory.length - 1];
    setRedoHistory(prev => prev.slice(0, -1));
    setUndoHistory(prev => [...prev, lastAction]);

    switch (lastAction.action) {
      case 'add':
        canvas.add(lastAction.object);
        break;

      case 'remove':
        canvas.remove(lastAction.object);
        break;

      case 'modify':
        if (lastAction.state) {
          lastAction.object.set(lastAction.state);
          lastAction.object.setCoords();
        }
        break;
    }

    // 恢复历史记录
    canvas.on('object:added', handleAdded);
    canvas.on('object:removed', handleRemoved);
    canvas.on('object:modified', handleModified);

    canvas.requestRenderAll();
  }
};

useEffect(() => {
  const handleKeyDown = (e: KeyboardEvent) => {
    if (!canvas) return;

    const activeObject = canvas.getActiveObject();
    
 
    // 处理文本编辑相关按键
    if (activeObject && activeObject.type === 'textbox') {
      const textbox = activeObject as Textbox;
      
      // 如果正在编辑文本，允许正常输入
      if (textbox.isEditing) {
        // 只阻止全局快捷键
        if ((e.ctrlKey || e.metaKey) && (e.key === 'c' || e.key === 'z' || e.key === 'Z')) {
          e.preventDefault();
        }
        return;
      }

      // 处理全局快捷键
      e.preventDefault();

      // 复制 Ctrl+C / Cmd+C
      if ((e.ctrlKey || e.metaKey) && e.key === 'c') {
        handleCopy();
      }
      // 撤销 Ctrl+Z / Cmd+Z
      else if ((e.ctrlKey || e.metaKey) && e.key === 'z' && !e.shiftKey) {
        handleUndo();
      }
      // 重做 Ctrl+Shift+Z / Cmd+Shift+Z
      else if ((e.ctrlKey || e.metaKey) && e.shiftKey && e.key === 'Z') {
        handleRedo();
      }
      return;
    }

    // 处理全局快捷键
    e.preventDefault();

    // 复制 Ctrl+C / Cmd+C
    if ((e.ctrlKey || e.metaKey) && e.key === 'c') {
      handleCopy();
    }
    // 撤销 Ctrl+Z / Cmd+Z
    else if ((e.ctrlKey || e.metaKey) && e.key === 'z' && !e.shiftKey) {
      handleUndo();
    }
    // 重做 Ctrl+Shift+Z / Cmd+Shift+Z
    else if ((e.ctrlKey || e.metaKey) && e.shiftKey && e.key === 'Z') {
      handleRedo();
    }
    // 上下左右移动
    else if (e.key === 'ArrowUp' || e.key === 'ArrowDown' || e.key === 'ArrowLeft' || e.key === 'ArrowRight') {
      if (activeObject) {
        const delta = 1; // 移动步长
        const newTop = activeObject.top || 0;
        const newLeft = activeObject.left || 0;

        if (e.key === 'ArrowUp') activeObject.set('top', newTop - delta);
        else if (e.key === 'ArrowDown') activeObject.set('top', newTop + delta);
        else if (e.key === 'ArrowLeft') activeObject.set('left', newLeft - delta);
        else if (e.key === 'ArrowRight') activeObject.set('left', newLeft + delta);

        canvas.renderAll();
      }
    }
  };

  document.addEventListener('keydown', handleKeyDown);
  return () => {
    document.removeEventListener('keydown', handleKeyDown);
  };
}, [canvas]);



  return (
  
    <div className="w-full mx-auto px-8 sm:px-6 md:px-12 lg:px-24 xl:border xl:border-gray-200 text-base md:text-lg">
      <TooltipProvider>

        <div className="pt-4">
        
          <div className="flex flex-row gap-2 my-2 justify-start">
            <Tooltip>
              <TooltipTrigger asChild>
                <Button
                  variant={isPc ? "default" : "secondary"}
                  onClick={() => setSize('pc')}
                >
                   <Monitor className="h-4 w-4" />
                </Button>
              </TooltipTrigger>
              <TooltipContent>切换为电脑端封面比例</TooltipContent>
            </Tooltip>

            <Tooltip>
              <TooltipTrigger asChild>
                <Button
                  variant={!isPc ? "default" : "secondary"}
                  onClick={() => setSize('phone')}
                >
                  <Smartphone className="h-4 w-4" />
                </Button>
              </TooltipTrigger>
              <TooltipContent>切换为手机端封面比例</TooltipContent>
            </Tooltip>

            <Tooltip>
              <TooltipTrigger asChild>
                <Button variant="secondary" onClick={clearBg}>
                <Eraser className="h-4 w-4" />
                </Button>
              </TooltipTrigger>
              <TooltipContent>清除当前背景图片</TooltipContent>
            </Tooltip>

            <Separator orientation="vertical" className="h-8 mx-2" />
            <Tooltip>
              <TooltipTrigger asChild>
                <Button variant="ghost" onClick={addText}>
                <Type className="h-4 w-4" />
                </Button>
              </TooltipTrigger>
              <TooltipContent>添加文本</TooltipContent>
            </Tooltip>

            <Tooltip>
              <TooltipTrigger asChild>
                <Button variant="ghost" asChild>
                  <Label htmlFor="file-input" className="cursor-pointer">
                  <ImageIcon className="h-4 w-4" />
                  </Label>
                </Button>
              </TooltipTrigger>
              <TooltipContent>添加图片</TooltipContent>
            </Tooltip>

            <Separator orientation="vertical" className="h-8 mx-2" />

            <Tooltip>
              <TooltipTrigger asChild>
                <Button variant="ghost" onClick={() => setShowGrid(!showGrid)}>
                <Grid className="h-4 w-4" />
                </Button>
              </TooltipTrigger>
              <TooltipContent>显示/隐藏网格</TooltipContent>
            </Tooltip>

            <Tooltip>
            <TooltipTrigger asChild>
                <Button variant="ghost" onClick={() => {
                  if (canvas) {
                    const activeObject = canvas.getActiveObject();
                    if (activeObject) {
                      canvas.bringObjectToFront(activeObject)
                      canvas.renderAll();
                    }
                  }
                }}>
                  <Layers className="h-4 w-4" />
                </Button>
              </TooltipTrigger>
              <TooltipContent>将选中元素置顶</TooltipContent>
            </Tooltip>

            <Tooltip>
              <TooltipTrigger asChild>
                <Button variant="ghost" onClick={() => {
                  if (canvas) {
                    const activeObject = canvas.getActiveObject();
                    if (activeObject) {
                      // 删除单个对象
                      canvas.remove(activeObject);
                      canvas.renderAll();
                    } else {
                      toast({
                        title: "请先选择一个对象",
                        variant: "destructive",
                      });
                    }
                  }
                }}>
                  <Trash2 className="h-4 w-4" />
                </Button>
              </TooltipTrigger>
              <TooltipContent>删除选中元素</TooltipContent>
            </Tooltip>

            <Separator orientation="vertical" className="h-8 mx-2" />

            <Tooltip>
              <TooltipTrigger asChild>
                <Button variant="ghost" onClick={handleUndo} disabled={undoHistory.length === 0}>
                <Undo2 className="h-4 w-4" />
                </Button>
              </TooltipTrigger>
              <TooltipContent>撤销操作</TooltipContent>
            </Tooltip>

            <Tooltip>
              <TooltipTrigger asChild>
                <Button variant="ghost" onClick={handleRedo} disabled={redoHistory.length === 0}>
                <Redo2 className="h-4 w-4" />
                </Button>
              </TooltipTrigger>
              <TooltipContent>重做操作</TooltipContent>
            </Tooltip>
            <Tooltip>
              <TooltipTrigger asChild>
                <Button variant="ghost" onClick={() => {
                  if (canvas) {
                    setShowGrid(false);
                    canvas.forEachObject(obj => {
                      if (obj.type === 'grid') {
                        canvas.remove(obj);
                      }
                    });
                    canvas.renderAll();
                    const dataURL = canvas.toDataURL({
                      format: 'png',
                      quality: 1.0,
                      multiplier: 2
                    });
                    const link = document.createElement('a');
                    link.href = dataURL;
                    link.download = 'cover.png';
                    link.click();
                  }
                }}>
                  <Download className="h-4 w-4" />
                </Button>
              </TooltipTrigger>
              <TooltipContent>导出当前设计为PNG</TooltipContent>
            </Tooltip>

            <Input
              id="file-input"
              type="file"
              accept="image/*,svg/*"
              className="hidden"
              onChange={handleImageUpload}  
            />

            <Separator orientation="vertical" className="h-8 mx-2" />

            <Dialog open={dialogOpen} onOpenChange={setDialogOpen}>
                  <DialogTrigger asChild>
                    
                    <Button variant="default">
                      模板
                    </Button>
                  </DialogTrigger>
                  <DialogContent className="sm:max-w-[90%]">
                    <DialogHeader>
                      <DialogTitle>视频封面模板列表</DialogTitle>
                    </DialogHeader>
                    <div className="grid grid-cols-2 sm:grid-cols-3 lg:grid-cols-4 gap-4 w-full px-4 md:px-6 mx-auto py-6">
                      {templates.map((template) => (
                        <div
                          key={template.name}
                          className="group relative bg-white dark:bg-gray-950 rounded-lg overflow-hidden shadow-sm hover:shadow-md transition-shadow duration-300 cursor-pointer"
                          onClick={() => applyTemplate(template)}
                        >
                          {template.image && (
                            <div className="relative aspect-[4/3]">
                              <div className="aspect-[4/3] w-full">
                                <img
                                  src={template.image}
                                  alt={template.title}
                                  className="w-full h-full object-cover transition-transform duration-300 group-hover:scale-105"
                                  loading="lazy"
                                />
                              </div>
                              <div className="absolute inset-0 bg-black/20 group-hover:bg-black/30 transition-colors duration-300" />
                            </div>
                          )}
                          <div className="p-3">
                            <h3 className="font-semibold text-base md:text-lg text-gray-900 dark:text-gray-100">
                              {template.title}
                            </h3>
                            <div className="mt-1 flex items-center justify-between">
                              <span className="text-xs text-gray-500 dark:text-gray-400">
                                点击应用模板
                              </span>
                              <div className="w-5 h-5 flex items-center justify-center rounded-full bg-gray-100 dark:bg-gray-800">
                                <svg
                                  className="w-3 h-3 text-gray-500 dark:text-gray-400"
                                  fill="none"
                                  stroke="currentColor"
                                  viewBox="0 0 24 24"
                                >
                                  <path
                                    strokeLinecap="round"
                                    strokeLinejoin="round"
                                    strokeWidth={2}
                                    d="M14 5l7 7m0 0l-7 7m7-7H3"
                                  />
                                </svg>
                              </div>
                            </div>
                          </div>
                        </div>
                      ))}
                    </div>
                  </DialogContent>
                </Dialog>

            <DropdownMenu>
              <DropdownMenuTrigger asChild>
                <Button variant="ghost">更多</Button>
              </DropdownMenuTrigger>
              <DropdownMenuContent>
              
              <DropdownMenuItem onClick={() => {
                const input = document.createElement('input');
                input.type = 'file';
                input.accept = '.json';
                input.onchange = (e) => {
                  const file = (e.target as HTMLInputElement).files?.[0];
                  if (file) {
                    toast({
                      title: "正在导入...",
                      variant: "default",
                    });

                    const reader = new FileReader();
                    reader.onload = async (event) => {
                      if (canvas && event.target?.result) {
                        try {
                          const json = JSON.parse(event.target.result as string);
                          canvas.clear();
                          await canvas.loadFromJSON(json);
                          canvas.requestRenderAll();
                          toast({
                            title: "导入成功",
                            variant: "default",
                          });
                        } catch (error) {
                          console.error('导入失败:', error);
                          toast({
                            title: "导入失败",
                            variant: "destructive",
                          });
                        }
                      }
                    };
                    reader.readAsText(file);
                  }
                };
                input.click();
              }}>
                导入
              </DropdownMenuItem>
                <DropdownMenuItem onClick={() => {
                  if (canvas) {
                    const json = JSON.stringify(canvas.toJSON());
                    const blob = new Blob([json], { type: 'application/json' });
                    const link = document.createElement('a');
                    link.href = URL.createObjectURL(blob);
                    link.download = 'cover.json';
                    link.click();
                  }
                }}>
                  导出JSON
                </DropdownMenuItem>
               
              </DropdownMenuContent>
            </DropdownMenu>
          </div>

          <div className={`flex p-0 w-full ${isPc ? 'flex-col xl:flex-row' : 'md:flex-row'}`}>
            <div className="w-full overflow-hidden">
              <canvas ref={canvasRef} className="w-full  rounded-md border border-gray-300" />
            </div>
            <div className={isPc ? 'w-full  xl:w-1/3 lg:pl-4' : 'w-full md:w-1/4 pl-4'}>
            <div className="space-y-4">
              <div>
                <Label className="mb-1">画布背景颜色:</Label>
                <Input
                  type="color"
                  value={bgColor}
                  onChange={(e) => {
                    const newColor = e.target.value;
                    setBgColor(newColor);
                    if (canvas) {
                      canvas.backgroundColor = newColor;
                      canvas.renderAll();
                    }
                  }}
                  className="h-10 w-full"
                />
              <div className="grid grid-cols-8 gap-2 mt-2">
                {[
                  'linear-gradient(45deg, #f6d365, #fda085)',
                  'linear-gradient(45deg, #f093fb, #f5576c)',
                  'linear-gradient(45deg, rgb(255, 184, 142), rgb(234, 87, 83))',
                  'linear-gradient(45deg, rgb(247, 186, 44), rgb(234, 84, 89))',
                  'linear-gradient(45deg, rgb(234, 152, 218), rgb(91, 108, 249))',
                  'linear-gradient(45deg, rgb(243, 105, 110), rgb(248, 169, 2))',
                  'linear-gradient(45deg, rgb(255, 215, 138), rgb(244, 118, 45))',
                  'linear-gradient(45deg, rgb(237, 227, 66), rgb(255, 81, 235))'
                ].map((gradient) => (
                  <div
                    key={gradient}
                    style={{ background: gradient }}
                    className="w-8 h-8 rounded-md border border-gray-300 cursor-pointer transition-transform hover:scale-110"
                    onClick={() => changeLinearBgColor(gradient)}
                  />
                ))}
              </div>
              </div>
              
              {selectedObject && (
                <div className="space-y-4">
                  {selectedObject.type === 'textbox' && (
                    <>
                      
                    <div>
                      <Label>字体:</Label>
                      <DropdownMenu>
                        <DropdownMenuTrigger asChild>
                          <Button variant="outline" className="w-full h-10">
                            {selectedObject ? (selectedObject as Textbox).fontFamily : textItem.fontFamily}
                          </Button>
                        </DropdownMenuTrigger>
                        <DropdownMenuContent className="w-56 max-h-64 overflow-y-auto">
                          {fontOptions.map((font) => (
                            <DropdownMenuItem
                              key={font}
                              onClick={() => {
                                if (selectedObject && selectedObject.type === 'textbox') {
                                  const textObj = selectedObject as Textbox;
                                  textObj.set('fontFamily', font);
                                  canvas?.renderAll();
                                  setTextItem(prev => ({
                                    ...prev,
                                    fontFamily: font
                                  }));
                                }
                              }}
                              style={{ fontFamily: font }}
                              className={selectedObject && (selectedObject as Textbox).fontFamily === font ? 'bg-gray-100' : ''}
                            >
                              {font}
                            </DropdownMenuItem>
                          ))}
                        </DropdownMenuContent>
                      </DropdownMenu>
                    </div>
                    </>
                  )}
                  <div>
                    <Label>颜色:</Label>
                    <Input
                      type="color"
                      value={selectedObject.fill?.toString() || '#000000'}
                      onChange={(e) => handleColorChange(e.target.value)}
                      className="h-10 w-full"
                    />
                  <div className="grid grid-cols-12 gap-2 mt-2">
                    {['#000000', '#ffffff', '#FFA500', '#5FCC8A', '#58B9F8', '#995DF6', '#75FB7E', '#EE7B69', '#E15B34', '#FFC0CB', '#F7D748', '#00FFFF'].map((color) => (
                      <div
                        key={color}
                        style={{ backgroundColor: color }}
                        className="w-6 h-6 rounded-full border border-gray-300 cursor-pointer transition-transform hover:scale-110"
                        onClick={() => handleColorChange(color)}
                      />
                    ))}
                  </div>
                  </div>
                  <div className="space-y-2">
                      <div>
                        <Label>阴影模糊度: {selectedObject.shadow?.blur || 0}</Label>
                        <input
                          type="range"
                          min="0"
                          max="20"
                          value={selectedObject.shadow?.blur || 0}
                          onChange={(e) => {
                            if (selectedObject) {
                              const newShadow = new Shadow({
                                ...selectedObject.shadow,
                                blur: parseInt(e.target.value)
                              });
                              selectedObject.set('shadow', newShadow);
                              canvas?.renderAll();
                              if (selectedObject.type === 'textbox') {
                                setTextItem(prev => ({
                                  ...prev,
                                  shadow: {
                                    ...prev.shadow,
                                    blur: parseInt(e.target.value)
                                  }
                                }));
                              } else if (selectedObject.type === 'image') {
                                setImageItem(prev => ({
                                  ...prev,
                                  shadow: {
                                    ...prev.shadow,
                                    blur: parseInt(e.target.value)
                                  }
                                }));
                              }
                            }
                          }}
                          className="w-full"
                        />
                      </div>
                      <div>
                        <Label>阴影偏移量: {selectedObject.shadow?.offsetX || 0}</Label>
                        <input
                          type="range"
                          min="0"
                          max="20"
                          value={selectedObject.shadow?.offsetX || 0}
                          onChange={(e) => {
                            if (selectedObject) {
                              const newShadow = new Shadow({
                                ...selectedObject.shadow,
                                offsetX: parseInt(e.target.value),
                                offsetY: parseInt(e.target.value)
                              });
                              selectedObject.set('shadow', newShadow);
                              canvas?.renderAll();
                              if (selectedObject.type === 'textbox') {
                                setTextItem(prev => ({
                                  ...prev,
                                  shadow: {
                                    ...prev.shadow,
                                    offsetX: parseInt(e.target.value),
                                    offsetY: parseInt(e.target.value)
                                  }
                                }));
                              } else if (selectedObject.type === 'image') {
                                setImageItem(prev => ({
                                  ...prev,
                                  shadow: {
                                    ...prev.shadow,
                                    offsetX: parseInt(e.target.value),
                                    offsetY: parseInt(e.target.value)
                                  }
                                }));
                              }
                            }
                          }}
                          className="w-full"
                        />
                      </div>
                    </div>

                    <div className="flex gap-4 items-center">
                  <div className="flex-1">
                    <Label>边框颜色</Label>
                    <input
                      type="color"
                      value={selectedObject?.stroke?.toString() || '#000000'}
                      onChange={(e) => {
                        if (selectedObject) {
                          selectedObject.set('stroke', e.target.value);
                          canvas?.renderAll();
                          // 更新本地状态以保持同步
                          if (selectedObject.type === 'textbox') {
                            setTextItem(prev => ({
                              ...prev,
                              stroke: e.target.value
                            }));
                          } else if (selectedObject.type === 'image') {
                            setImageItem(prev => ({
                              ...prev,
                              stroke: e.target.value
                            }));
                          }
                        }
                      }}
                      className="w-full"
                    />
                  </div>
                  <div className="flex-1">
                    <Label>边框粗细: {selectedObject?.strokeWidth || 0}</Label>
                    <input
                      type="range"
                      min="0"
                      max="20"
                      value={selectedObject?.strokeWidth || 0}
                      onChange={(e) => {
                        if (selectedObject) {
                          const newWidth = parseInt(e.target.value);
                          selectedObject.set('strokeWidth', newWidth);
                          canvas?.renderAll();
                          // 更新本地状态以保持同步
                          if (selectedObject.type === 'textbox') {
                            setTextItem(prev => ({
                              ...prev,
                              strokeWidth: newWidth
                            }));
                          } else if (selectedObject.type === 'image') {
                            setImageItem(prev => ({
                              ...prev,
                              strokeWidth: newWidth
                            }));
                          }
                        }
                      }}
                      className="w-full"
                    />
                  </div>
                </div>


                </div>
              )}
            </div>
          </div>
          </div>
        </div>
      </TooltipProvider>
    </div>

  );
};

export default HomePage;